package com.itphy.controller;

import com.alibaba.fastjson.JSON;
import com.itphy.common.R;
import com.itphy.common.wechat.*;
import com.itphy.common.wechat.template.GoodsIssueNotice;
import com.itphy.mapper.WechatSendLogMapper;
import com.itphy.mapper.WechatTemplateMapper;
import com.itphy.pojo.WechatSendLog;
import com.itphy.service.WechatService;
import com.itphy.util.Maps;
import com.itphy.util.XmlUtilDom4j;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.itphy.common.wechat.WechatEnum.*;

@Controller
@Slf4j
public class WeChatController {

    @Inject
    private WechatService wechatService;
    @Inject
    private WechatSendLogMapper wechatSendLogMapper;
    @Inject
    private WechatTemplateMapper wechatTemplateMapper;

    /**
     * 微信公众号接入验证
     * @param wechatParam
     */
    private boolean checkToken(WechatParam wechatParam){
        String[] params=new String[]{TOKEN,wechatParam.getTimestamp(),wechatParam.getNonce()};
        Arrays.sort(params);
        String src=params[0]+params[1]+params[2];
        StringBuilder builder=new StringBuilder();
        try {
            MessageDigest sha1 = MessageDigest.getInstance("sha1");
            byte[] digest = sha1.digest(src.getBytes());
            char[] chars=new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            for(byte b : digest){
                builder.append(chars[(b>>4)&15]);
                builder.append(chars[b&15]);
            }
            return wechatParam.getSignature().equals(builder.toString());
        } catch (NoSuchAlgorithmException e) {
            return false;
        }
    }

    /**
     * 微信公众号接入验证
     * @param wechatParam
     */
    @Mapping(value = "/wechat",method = MethodType.GET)
    public String ping(WechatParam wechatParam){
        if(checkToken(wechatParam)){
            return wechatParam.getEchostr();
        }
        return "";
    }

    /**
     * 微信公众号消息监听统一入口
     * @param ctx
     */
    @Mapping(value = "/wechat",method = MethodType.POST)
    public String handler(Context ctx){
        try {
            InputStream is = ctx.bodyAsStream();
            Document document = XmlUtilDom4j.parseXML(is);
            Map<String, Object> data = XmlUtilDom4j.parseToMap(document);
            String xmlMsg="";
            if("谁最帅".equals(data.get("Content"))){
                xmlMsg=new TextMessage().setContent("乐博")
                        .setFromUserName(data.get("ToUserName").toString())
                        .setToUserName(data.get("FromUserName").toString()).toString();
            }
            return xmlMsg;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    @Mapping(value = "/test",method = MethodType.POST)
    public R sendTemplate(Context ctx){
        GoodsIssueNotice goodsIssueNotice = ctx.paramAsBean(GoodsIssueNotice.class);
        TemplateMessage template = new TemplateMessage()
                .setTemplate_id(GoodsIssueNotice.KEY)//设置模板id
                .setTouser(goodsIssueNotice.getOpenId())
                .setUrl("http://love.itphy.com/group1/M00/00/00/rBEPcmCd87qAL-CVAAF1-vb2Wcs718.pdf")//设置点击消息跳转的url
                .setData(Maps.getTemplateMessageData(goodsIssueNotice, wechatTemplateMapper.queryBeanByKey(GoodsIssueNotice.KEY).getTemplate()));//渲染模板参数
        WechatSendLog log=new WechatSendLog()
                .setOpenId(goodsIssueNotice.getOpenId())
                .setBussId(goodsIssueNotice.getBussId())
                .setContent(JSON.toJSONString(template))
                .setTempKey(GoodsIssueNotice.KEY);
        try {
            boolean flag = wechatService.sendTemplateMessage(template);
            if(flag){
                log.setStatus(1);
                wechatSendLogMapper.insert(log);
                return R.ok();
            }
            log.setStatus(0);
            wechatSendLogMapper.insert(log);
            return R.fail();
        }catch (Exception e){
            log.setStatus(0);
            wechatSendLogMapper.insert(log);
            return R.fail();
        }
    }

}
